﻿using DotNetty.Buffers;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels.Sockets;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Codecs;

namespace ShaoLuNettyServer
{
    public class DotNettyClient
    {
        private MultithreadEventLoopGroup group;
        private Bootstrap bootstrap;
        private IChannel channel;

        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public async Task StartAsync()
        {
            group = new MultithreadEventLoopGroup();

            try
            {
                bootstrap = new Bootstrap()
                    .Group(group)
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                        pipeline.AddLast(new StringDecoder(Encoding.UTF8));
                        pipeline.AddLast(new LengthFieldPrepender(4));
                        pipeline.AddLast(new StringEncoder(Encoding.UTF8));
                        pipeline.AddLast(new DotNettyClientHandler());
                    }));

                channel = await bootstrap.ConnectAsync("127.0.0.1", 8888);
                string clientName = "小王";
                byte[] nameBytes = Encoding.UTF8.GetBytes(clientName);
                await channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(nameBytes));

                Console.WriteLine("Connected to server.");
                Logger.Info("Connected to server.");

                // 发送消息给服务器
                SendMessage("我是客户端");

                // 停顿一段时间，模拟客户端的其他操作
                await Task.Delay(5000);

                // 发送更多消息给服务器
                SendMessage("我发 发阿飞");

                //关闭客户端连接
                //await channel.CloseAsync();
                //Console.WriteLine("Client connection closed.");
            }
            finally
            {
                await group.ShutdownGracefullyAsync();
            }
        }

        public void SendMessage(string message)
        {
            if (channel != null && channel.Open)
            {
                channel.WriteAndFlushAsync(message);
                Console.WriteLine("Sent message to server: " + message);
                Logger.Info("Sent message to server: " + message);
            }
        }
    }
}
